package com.epro.dx.activity.coupon.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.epro.dx.R;
import com.epro.dx.activity.HomeActivity;
import com.epro.dx.activity.LandingPageActivity;
import com.epro.dx.activity.LoginActivity;
import com.epro.dx.activity.ProductListActivity;
import com.epro.dx.activity.coupon.adapter.CouponMarketListAdapter;
import com.epro.dx.fragment.BaseLoadAndEmptyDataFragment;
import com.epro.dx.listenner.OnItemViewClickListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CatelogModel;
import com.weipu.common.facade.model.CouponActiveModel;
import com.weipu.common.facade.model.CouponModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("ValidFragment")

public class CouponMarketFragment extends BaseLoadAndEmptyDataFragment implements OnItemViewClickListenner {
    private static final String TAG = "CouponMarketFragment";
    private RelativeLayout emptyPage;//无数据布局
    private RelativeLayout haveDataPage;//有数据布局
    private View rootView;//根布局
    private PullToRefreshListView listView;//coupon列表
    public int pageIndex = 0;//查询起始页
    private int pageSize = 16;//每页查询数据条数
    private ArrayList<CouponModel> coupons;//用于存储一次查询到的Coupon集合
    private ArrayList<CouponModel> couponList = new ArrayList<CouponModel>();
    private CouponMarketListAdapter couponMarketListAdapter;//Coupon列表数据适配器
    private int currentPage;
    private boolean isLoading = false;
//	private ProgressBar progressLoad;

    private boolean fromResult = false;

    public CouponMarketFragment(int currentPage) {
        this.currentPage = currentPage;
    }

    public CouponMarketFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            this.currentPage = savedInstanceState.getInt("CurrentPage");
        }
        if (rootView == null) {
            rootView = inflate(R.layout.fragment_coupon);
            initView();
            initEvent();
            initData(false);
        } else {
            initData(true);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
//		super.onSaveInstanceState(outState);
        outState.putInt("CurrentPage", currentPage);
    }
//	@Override
//	public void onResume() {
//		initData(false);
//		super.onResume();
//	}

    /**
     * 加载事件
     */
    private void initEvent() {
        //coupon列表的下拉刷新与上拉加载
        listView.setScrollingWhileRefreshingEnabled(true);
        listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                isLoading = true;
                pageIndex = 0;
                initData(true);
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                isLoading = true;
                pageIndex += 1;
                initData(false);
            }
        });
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                if (couponList.size() <= position - 1) {
                    return;
                }
                CouponModel couponModel = couponList.get(position - 1);
                if (null != couponModel) {
                    AsyncTaskUtil.executeTask(new FindCouponActiveInfo(couponModel.getCouponCode()));
                }
            }
        });
//		 listView.getRefreshableView().setSelector(null);
        listView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
        listView.getRefreshableView().setCacheColorHint(getResources().getColor(R.color.transparent));
    }

    /**
     * 获取Coupon对应活动信息
     *
     * @author huangfei
     */
    class FindCouponActiveInfo extends AsyncTask<Void, Void, String> {
        private CouponActiveModel couponActiveModel;
        private String couponCode;
        private List<ProductModel> productLists;

        public FindCouponActiveInfo(String couponCode) {
            this.couponCode = couponCode;
        }

        @Override
        protected void onPreExecute() {
            showLoadingLayout(null);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                couponActiveModel = ProviderFactory.createCouponServiceProvider().FindDiscountProducts(couponCode, Constant.LIST_PAGE_COUNT, 0, 0, "d=Popularity",
                        ActivityUtil.getCustomerID(), OnekeyFilterLocalUtil.getFilterState(getActivity()), OnekeyFilterLocalUtil.getLocalCategoryIds(getActivity()));
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (isAdded()) {
//				hideWaitingDialog();
                hideAllLayout();
                if ("0".equals(result)) {
                    if (null != couponActiveModel) {
                        boolean isWholeSite = couponActiveModel.isIsWholeSite();
                        Logger.i(TAG, isWholeSite + "  isWholeSite");
                        Intent intent = new Intent();
                        if (couponActiveModel.isIsMvp()) {//针对MVP的Coupon
                            intent.setClass(getActivity(), ProductListActivity.class);
                            intent.putExtra(Constant.PRODUCTLIST_TYPE, Constant.TYPE_MVP24HRS);
                            intent.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_HOME);
                            intent.putExtra(Constant.PRODUCT_TITLE, "MVP 24hrs");
                            startActivity(intent);
                            return;
                        }
                        if (!isWholeSite) {
                            int currencyCategoryId = couponActiveModel.getCurrencyCategoryId();
                            Logger.i(TAG, "currencyCategoryId " + currencyCategoryId);
                            List<CatelogModel> cates = couponActiveModel.getCategories();
                            productLists = couponActiveModel.getProducts();
                            Logger.i(TAG, currencyCategoryId + " " + cates + " " + productLists);
                            if (null != productLists) {
                                if (currencyCategoryId == 0) {
                                    intent.setClass(getActivity(), ProductListActivity.class);
                                    intent.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_COUPON);
                                } else {
                                    if (null == cates) {
                                        return;
                                    }
                                    if (cates.size() == 1) {
                                        intent.setClass(getActivity(), ProductListActivity.class);
                                        intent.putExtra("catalogId", cates.get(0).getBrowseID());
                                        intent.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_COUPON);
                                        intent.putExtra(Constant.PRODUCT_TITLE, cates.get(0).getShortName());
                                    } else {
                                        intent.setClass(getActivity(), LandingPageActivity.class);
                                        ArrayList<CatelogModel> catelist = (ArrayList<CatelogModel>) cates;
                                        intent.putParcelableArrayListExtra("categorylist", catelist);
                                    }
                                }
                                ArrayList<ProductModel> prductlist = (ArrayList<ProductModel>) productLists;
                                intent.putParcelableArrayListExtra("productlist", prductlist);
                                intent.putExtra("CouponCode", couponCode);
                                intent.putExtra("CurrencyCode", couponActiveModel.getCurrencyCode());
                                intent.putExtra("CurrencyCodeStr", couponActiveModel.getCurrencyCodeStr());
                                startActivity(intent);
                            }

                        } else {
                            intent.setClass(getActivity(), HomeActivity.class);
                            intent.putExtra(HomeActivity.CURRENT_TAB_TAG,
                                    getString(HomeActivity.titleArray[0]));
                            startActivity(intent);
                        }
                    }
                } else {
                    AlertToast.alert(getActivity(),
                            ServerConstant.ReturnCode.MESSAGEMAP
                                    .get(result));
                }
            }
            super.onPostExecute(result);
        }

    }

    /**
     * 初始化UI
     */
    private void initView() {
        listView = (PullToRefreshListView) rootView.findViewById(R.id.coupon_couponlist);
//		progressLoad=(ProgressBar) rootView.findViewById(R.id.loading_progress);
        haveDataPage = (RelativeLayout) rootView.findViewById(R.id.coupon_page_havedata);
        couponMarketListAdapter = new CouponMarketListAdapter(getActivity(), couponList);
        couponMarketListAdapter.setViewClickListenner(this);
        listView.setAdapter(couponMarketListAdapter);
    }

    /**
     * 加载数据
     */
    public void initData(boolean isPulldown) {
        if (currentPage == 0) {
            // 连接接服务器获取数据
            AsyncTaskUtil.executeTask(new GetCouponList(isPulldown));
        }
    }

    /**
     * @param currentPage 页面编号
     *                    设置当前的页面编号
     */
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    /**
     * @author Tony
     *         获取Coupon列表的任务
     */
    class GetCouponList extends AsyncTask<Void, Void, String> {

        private boolean isPulldown;

        public GetCouponList(boolean isPulldown) {
            this.isPulldown = isPulldown;

        }

        @Override
        protected void onPreExecute() {
            if (!isLoading) {
                if (couponList.size() == 0 || haveDataPage.getVisibility() != View.VISIBLE) {
                    showLoadingLayout(haveDataPage);
                }/*else{
//					progressLoad.setVisibility(View.VISIBLE);
				}*/
            }

//				showWaitingDialog();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                coupons = ProviderFactory.createCouponServiceProvider().FindMarketCoupons(ActivityUtil.getCustomerID(), 1, 1, pageIndex, pageSize);
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (isAdded()) {
                hideAllLayout();
//				    progressLoad.setVisibility(View.GONE);
                if (isLoading) {
                    isLoading = false;
                    listView.onRefreshComplete();
                }
                if ("0".equals(result)) {
                    if (coupons != null) {
                        if (isPulldown) {
                            couponList.clear();
                        }
                        couponList.addAll(coupons);
                        if (coupons.size() < pageSize) {
                            //如果一次获取到的数据条数小于设定值，说明没有更多了，禁止上拉加载更多的操作
                            listView.setMode(Mode.PULL_FROM_START);
                        } else {
                            listView.setMode(Mode.BOTH);
                        }
                    }
                    if (couponList.size() == 0) {//没有数据
                        showEmptyLayout(haveDataPage, R.string.coupon_market_no_coupon, R.drawable.couponmarket_no_coupon);
                    } else {//有数据
                        hideAllLayout(haveDataPage);
//							progressLoad.setVisibility(View.GONE);
                        couponMarketListAdapter.notifyDataSetChanged();
                    }
                } else {
                    if (pageIndex == 0 && (TextUtils.equals(ServerConstant.ReturnCode.
                            VALIDATOR_UNKONW_ERROR, result) || TextUtils.equals(ServerConstant.ReturnCode.
                            CLIENT_NET_UN_AVAILABLE, result))) {
                        if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)) {
                            showErrorLayout(haveDataPage, R.string.internet_error,
                                    R.string.internet_suggest, R.drawable.no_internet);
                        } else {
                            showErrorLayout(haveDataPage, R.string.server_busy,
                                    R.string.server_suggest, R.drawable.no_internet);
                        }
                        retryBtn.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {
                                initData(false);
                            }
                        });
                    } else {
                        listView.onRefreshComplete();
                        pageIndex--;
                        listView.setMode(Mode.BOTH);
                        AlertToast.alert(getActivity(),
                                ServerConstant.ReturnCode.MESSAGEMAP
                                        .get(result));
                    }
                }
            }
            super.onPostExecute(result);
        }

    }

    /**
     * @author hf
     *         获取Coupon
     */
    class BindCouponTask extends BaseNeedReLoginTask {

        private String couponCode;
        private int position;

        public BindCouponTask(String couponCode, int position) {
            this.couponCode = couponCode;
            this.position = position;
        }

        @Override
        protected void onPreExecute() {
//			showWaitingDialog();
            showLoadingLayout(null);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                ProviderFactory.createCouponServiceProvider().BindCoupon(ActivityUtil.getCustomerID(), couponCode,
                        ActivityUtil.getCustomerToken());
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (isAdded()) {
                hideAllLayout();
                if ("0".equals(result)) {
                    //这样领完coupon以后，会消失，与需求不符
//                    if (couponList.size() > position) {
//                        couponList.remove(position);
//                        couponMarketListAdapter.notifyDataSetChanged();
//                    }

                    if (couponList.size() <= 0) {
                        isLoading = false;
                        pageIndex = 0;
                        initData(false);
                    }
//					if(!fromResult){
                    AlertToast.alert(getActivity(),
                            R.string.get_coupon_successed);
//					}

                    //领完coupon以后，重新请求网络，拿到最新的数据，展示在界面上
                    initData(true);
                } else if (!isRelogin) {
//					if(!fromResult){//未登录，登陆过后重新走的领取逻辑，不作提示处理
                    AlertToast.alert(getActivity(),
                            ServerConstant.ReturnCode.MESSAGEMAP
                                    .get(result));
//					}
                }
                if (fromResult) {
                    //重新加载数据
                    initData(true);
                    fromResult = false;
                }
            }
        }

        @Override
        protected Context setContext() {
            return getActivity();
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new BindCouponTask(couponCode, position);
        }

    }

    @Override
    public void onViewClick(int position) {
        if (null == couponList) {
            return;
        }
        CouponModel cModel = couponList.get(position);
        if (null == cModel) {
            return;
        }
        String couponCode = cModel.getCouponCode();
        if (ActivityUtil.isLogin(getActivity())) {
            AsyncTaskUtil.executeTask(new BindCouponTask(couponCode, position));
        } else {
            //没有登陆跳转到登陆页面，登陆成功后返回当前页面
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            intent.putExtra(
                    ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                    ServerConstant.Parameter.PARAMETER_ACTION_TYPE_COUPONMARKET);
            intent.putExtra("CouponCode", couponCode);
            intent.putExtra("CouponIndex", position);
            startActivityForResult(intent, 10);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        fromResult = true;
        if (null != data) {
            String couponCode = data.getStringExtra("CouponCode");
            int position = data.getIntExtra("CouponIndex", -1);
            if (null != couponCode && position >= 0) {
                AsyncTaskUtil.executeTask(new BindCouponTask(couponCode, position));
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
